<template>
  <van-dialog
    v-model:show="show"
    title="请选择位置"
    show-cancel-button
    destroy-on-close>
    <div :id="mid" style="width: 100%; height: 65vh; margin-top: 10px"></div>
  </van-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import chongqing from "@/utils/chongqing.json";
import { getUserInfo } from "@/utils/userInfo.js";
import TianMapApi from '@/utils/TianMapApi.js'
// county?.properties.center
const mapConfig = {
  // center: [29.560014017912916, 106.55023002469534],
  center: [106.504962, 29.533155],
  zoom: 10,
  options: {
    minZoom: 8,
    maxZoom: 22
    // maxBounds: [[40.177945,118.402326],[39.841501,119.030708]]
  }
}
const userInfo = getUserInfo();
const county = chongqing.features.find(item => item.properties.adcode == userInfo.countyCode)

const props = defineProps({
  center: {
    type: Array,
    default: () => [],
  },

  // 是否开启点击事件
  isClick: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['mapClick'])

const show = ref(false)
const mid = ref(uuidv4())
const mapReady = ref(false)
// 初始化地图
function initMap() {
  nextTick(() => {
    TianMapApi.CreateMap(mid.value)
    mapReady.value = true

    // 当前区画边框
    // TianMapApi.addCountyBorder(county.geometry.coordinates)

    // 设置中心
    goCenter()

    // 自动绑定点击（按需）
    if (props.isClick) {
      bindClick()
    }
  })
  
}

// 设置中心点与标注
function goCenter() {
  if (!mapReady.value || !TianMapApi.map) return
  const [lng, lat] = props.center.length > 0 ? props.center : (county?.properties.center || mapConfig.center)

  // 添加标注
  if(lng && lat && props.center.length > 0) {
    TianMapApi.clearOverLays()
    TianMapApi.addMarker(lng, lat)
  }
  TianMapApi.map.panTo(new window.T.LngLat(lng, lat))
}

// 绑定地图点击事件
function bindClick() {
  if (!TianMapApi.map) return

  TianMapApi.onClick(([lng, lat]) => {
    // 获取地址信息
    // TianMapApi.getAddressByXY([lng, lat], (address) => {
    //   if (address.info === 'OK') {
    //     const info = address.regeocode.addressComponent
    //     const locationInfo = {
    //       regionCode: info.adcode,
    //       districtName: info.district,
    //       streetName: info.township,
    //       positionDesc: address.regeocode.formattedAddress,
    //       towncode: info.towncode,
    //     }
    //     console.log(locationInfo, '地址信息')
    //     emit('address', locationInfo)
    //   }
    // })

    emit('mapClick', [lng, lat])
    TianMapApi.clearOverLays()
    TianMapApi.addMarker(lng, lat)
  })
}

const open = () => {
  show.value = true
}

watch(() => show.value, () => {
  if (show.value) {
    initMap()
  } else {
    if (TianMapApi.map) {
      TianMapApi.clearOverLays()
      TianMapApi.offClick()
    }
  }
}, { deep: true, immediate: true })

defineExpose({
  open
})
</script>

<style scoped>
</style>
